//
//  NotificationViewController.m
//  YiqiMobile
//
//  Created by henry on 13-4-18.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "NotificationViewController.h"
#import "Config.h"
#import "Utility.h"
#include "DefineAction.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#define POPTONGZHIBUTTONGTAG 230
#import "NotificationViewController.h"
#import "Utility.h"
#import "Config.h"
@interface NotificationViewController ()

@end

@implementation NotificationViewController



- (void)viewDidLoad{
    [super viewDidLoad];
    self.navigationItem.titleView=[Utility getTitleView:@"公告/通知"];
    self.view.backgroundColor = UIColorFromRGB(0xfafafa);
        
    self.data0Array=[NSMutableArray array];
    self.data1Array=[NSMutableArray array];
    self.headerArray=[NSMutableArray array];
    [self.headerArray addObject:@"noti_gonggao.png"];
    [self.headerArray addObject:@"noti_list.png"];
    [self loadModel];
    float height=367-62;
    if (iPhone5) {
         height+=88;
    }
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 62,320,height)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor=[UIColor colorWithRed:228.0/255 green:228.0/255 blue:228.0/255 alpha:1.0];
    [self.view addSubview:self.tableView];
      
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(backToPre) normalImage:@"navback_normal.png" lightedImage:@"navback_hover.png" frame:CGRectMake(0, 0, 58, 29) title:nil tag:10]];
    self.navigationItem.leftBarButtonItem=backBarButtonItem;
    
    //UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(backToPre) normalImage:@"noti_save_normal.png" lightedImage:@"noti_save_hover.png" frame:CGRectMake(0, 0, 59, 30) title:nil tag:11]];
   // self.navigationItem.rightBarButtonItem=rightBarButtonItem;
    [self topView];
    [self dataListFromServer:ETZLISTBYEACTION andPage:1];
}

-(void) topView{
    [self.view addSubview:[Utility customButton:self action:@selector(popTongzhiView:) normalImage:@"publishnoti_normal.png" lightedImage:@"publishnoti_hover.png" frame:CGRectMake(12, 12, 145, 37) title:nil tag:POPTONGZHIBUTTONGTAG]];
    [self.view addSubview:[Utility customButton:self action:@selector(popTongzhiView:) normalImage:@"publishAdvice_normal.png" lightedImage:@"publishAdvice_hover.png" frame:CGRectMake(163, 12, 145, 37) title:nil tag:POPTONGZHIBUTTONGTAG+1]];
}

-(void) popTongzhiView:(UIButton*) sender{
    CreateTongzhiView *tongzhi=[[CreateTongzhiView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    tongzhi.delegate=self;
    if ([sender tag]==POPTONGZHIBUTTONGTAG) {
        tongzhi.type=0;
    }else{
        tongzhi.type=1;
    
    }
    [tongzhi showData];
    AppDelegate *appDelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate.window addSubview:tongzhi];
}

-(void)backToPre{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void) dataListFromServer:(NSString*)action andPage:(int)page{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility  getServerUrl],action];
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    [param setObject:app.quanziId forKey:@"id"];
    [param setObject:[NSString stringWithFormat:@"%d",page] forKey:@"jr.curPageNum"];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
    [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}

- (void)requestFinished:(id)context{
    [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            if ([[result objectForKey:@"method"] isEqualToString:ETZLISTBYEACTION]) {
                [self dataListFromServer:GGAOISTBYEACTION andPage:1];
                [self.data1Array removeAllObjects];
                [self.data1Array addObjectsFromArray:[result objectForKey:@"list"]];
                [self.tableView reloadData];

            }else if ([[result objectForKey:@"method"] isEqualToString:GGAOISTBYEACTION]) {
                [self.data0Array removeAllObjects];
                [self.data0Array addObjectsFromArray:[result objectForKey:@"list"]];
                [self.tableView reloadData];
            }
        
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}


- (void)loadModel{
    self.currentRow = -1;
    self.headViewArray = [[NSMutableArray alloc] init];
    for(int i = 0;i<self.headerArray.count ;i++){
        NSString *imageName=[self.headerArray objectAtIndex:i];
		HeadView* headview = [[HeadView alloc] init];
        headview.delegate = self;
		headview.section = i;
        if (i==0) {
            headview.open=YES;
        }
        [headview.backBtn  setBackgroundImage:[Utility imageNamed:imageName] forState:UIControlStateNormal];
        [headview.backBtn  setBackgroundImage:[Utility imageNamed:imageName] forState:UIControlStateSelected];
        [headview.backBtn  setBackgroundImage:[Utility imageNamed:imageName] forState:UIControlStateHighlighted];
		[self.headViewArray addObject:headview];
	}
}



#pragma mark - TableViewdelegate&&TableViewdataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HeadView* headView = [self.headViewArray objectAtIndex:indexPath.section];
    
    return headView.open?80:0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 29;
}


- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [self.headViewArray objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    HeadView* headView = [self.headViewArray objectAtIndex:section];
    if (section==0) {
        return headView.open?[self.data0Array count]:0;
    }else{
       return headView.open?[self.data1Array  count]:0;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.headViewArray count];
}



- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *indentifier = @"bowenmanageViewCell";
    BowenmanageViewCell *cell =(BowenmanageViewCell*)[tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        cell =[[BowenmanageViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    switch (indexPath.section) {
        case 0:{
            cell.button1.frame=CGRectMake(205, 16, 50, 20);
            
            [cell.button1 setImage:[Utility imageNamed:@"qz_goedit_normal.png"] forState:UIControlStateNormal];
            [cell.button1 setImage:[Utility imageNamed:@"qz_goedit_hover.png"] forState:UIControlStateSelected];
            [cell.button1 setImage:[Utility imageNamed:@"qz_goedit_hover.png"] forState:UIControlStateHighlighted];
            
            cell.button2.frame=CGRectMake(260, 16, 50, 20);
            [cell.button2 setImage:[Utility imageNamed:@"qz_publish_normal.png"] forState:UIControlStateNormal];
            [cell.button2 setImage:[Utility imageNamed:@"qz_publish_hover.png"] forState:UIControlStateSelected];
            [cell.button2 setImage:[Utility imageNamed:@"qz_publish_hover.png"] forState:UIControlStateHighlighted];
            break;
        }
        case 1:{
            cell.button1.frame=CGRectMake(205, 16, 49, 20);
            cell.button2.frame=CGRectMake(260, 16, 49, 20);
            [cell.button1  setImage:[Utility imageNamed:@"qz_zhiding_hover.png"] forState:UIControlStateNormal];
            [cell.button1  setImage:[Utility imageNamed:@"qz_zhiding_normal.png"] forState:UIControlStateSelected];
            [cell.button1  setImage:[Utility imageNamed:@"qz_zhiding_normal.png"] forState:UIControlStateHighlighted];
            [cell.button2 setImage:[Utility imageNamed:@"qz_hide_normal.png"] forState:UIControlStateNormal];
            [cell.button2 setImage:[Utility imageNamed:@"qz_hide_normal.png"] forState:UIControlStateSelected];
            [cell.button2 setImage:[Utility imageNamed:@"qz_hide_hover.png"] forState:UIControlStateHighlighted];
            break;
        }
    }
    HeadView *head = [self.headViewArray objectAtIndex:indexPath.section];
    if (head.open) {
        head.open = YES;
        UIImageView *imageView=(UIImageView*)[head viewWithTag:2000];
        imageView.image=[Utility imageNamed:@"quanziopen.png"];
    }
    cell.delegate=self;
    cell.indexPath=indexPath;
    if (indexPath.section==0) {
        NSDictionary *dict=[self.data0Array objectAtIndex:indexPath.row];
        cell.labelContent.text=[dict objectForKey:@"gg1"];
        //cell.labelDetail.text=[NSString stringWithFormat:@"%@ 阅读:%@  评论:%@  收藏:  %@",[Utility datefromSeconds:[dict objectForKey:@"etz2"] andDateFormat:@"yyyy-MM-dd mm:HH"],@"100",@"100",@"100"];
        cell.labelDetail.text=[NSString stringWithFormat:@"%@ ",[Utility datefromSeconds:[dict objectForKey:@"gg4"] andDateFormat:@"yyyy-MM-dd mm:HH"]];
           
    }else{
        NSDictionary *dict=[self.data1Array objectAtIndex:indexPath.row];
        cell.labelContent.text=[dict objectForKey:@"etz1"];
       // cell.labelDetail.text=[NSString stringWithFormat:@"%@ 阅读:%@  评论:%@  收藏:  %@",[Utility datefromSeconds:[dict objectForKey:@"etz2"] andDateFormat:@"yyyy-MM-dd mm:HH:ss"],@"100",@"100",@"100"];
         cell.labelDetail.text=[NSString stringWithFormat:@"%@ ",[Utility datefromSeconds:[dict objectForKey:@"etz2"] andDateFormat:@"yyyy-MM-dd mm:HH"]];
    }
   
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.currentRow = indexPath.row;
    [self.tableView reloadData];
}


#pragma mark - HeadViewdelegate
-(void)selectedWith:(HeadView *)view{
    self.currentRow = -1;
    if (view.open) {
        for(int i = 0;i<[self.headViewArray count];i++)
        {
            HeadView *head = [self.headViewArray objectAtIndex:i];
            head.open = NO;
            //[head.backBtn setBackgroundImage:[UIImage imageNamed:@"btn_momal"] forState:UIControlStateNormal];
            UIImageView *imageView=(UIImageView*)[head viewWithTag:2000];
            imageView.image=[Utility imageNamed:@"quanziFolder.png"];
        }
        [_tableView reloadData];
        return;
    }
    self.currentSection = view.section;
    [self reset];
    
}

//界面重置
- (void)reset
{
    for(int i = 0;i<[self.headViewArray count];i++)
    {
        HeadView *head = [self.headViewArray objectAtIndex:i];
        UIImageView *imageView=(UIImageView*)[head viewWithTag:2000];
        if(head.section == self.currentSection){
            head.open = YES;
            imageView.image=[Utility imageNamed:@"quanziopen.png"];
            
        }else {
            imageView.image=[Utility imageNamed:@"quanziFolder.png"];
            head.open = NO;
        }
        
    }
    [self.tableView reloadData];
}

//cell中按钮
-(void) buttonOfCellAction:(NSIndexPath*) indexpath andtag:(int) tag{
    NSLog(@"%d",tag);
}
//查看日志按钮
-(IBAction)viewLogAction:(id)sender{
    NSLog(@"%@",@"查看圈子日志");
    
}


-(UITextField*) customTextField:(CGRect) frame{
    
    UITextField *textFied = [[UITextField alloc] initWithFrame:frame];
    textFied.keyboardType=UIKeyboardAppearanceDefault;
    textFied.autocorrectionType = UITextAutocorrectionTypeNo;
    textFied.returnKeyType=UIReturnKeyNext;
    textFied.clearButtonMode=UITextFieldViewModeWhileEditing;
    textFied.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    textFied.backgroundColor=[UIColor  clearColor];
    textFied.borderStyle=UITextBorderStyleNone;
    textFied.textColor=[UIColor blackColor];
    textFied.font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    textFied.autocorrectionType=UITextAutocorrectionTypeNo;
    [textFied setBorderStyle:UITextBorderStyleNone];
    textFied.returnKeyType = UIReturnKeyNext;
    textFied.keyboardType=UIKeyboardAppearanceAlert;
    return textFied;
}
-(void) success:(int)flag{
    if (flag==0) {
         [self dataListFromServer:ETZLISTBYEACTION andPage:1];
    }else{
         [self dataListFromServer:GGAOISTBYEACTION andPage:1];
    }
}

- (void)dealloc{
    
}

@end
